import { defineStore } from 'pinia';
import {
  login as userLogin,
  logout as userLogout,
  LoginData,
} from '@/api/user';
import { setToken, clearToken } from '@/utils/auth';
import { removeRouteListener } from '@/utils/route-listener';
import { UserState } from './types';
import useAppStore from '../app';

let agentInfo = {};
const useUserStore = defineStore('user', {
  state: (): UserState => ({
    name: undefined,
    avatar: null,
    city_id: undefined,
    create_admin_id: undefined,
    createtime: undefined,
    id: undefined,
    loginfailure: undefined,
    loginip: undefined,
    logintime: undefined,
    mobile: undefined,
    type: undefined,
    updatetime: undefined,
    user_id: undefined,
    role: '',
  }),

  getters: {
    userInfo(state: UserState): UserState {
      return { ...state };
    },
  },

  actions: {
    switchRoles() {
      return new Promise((resolve) => {
        this.role = this.role === 'user' ? 'admin' : 'user';
        resolve(this.role);
      });
    },
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial);
    },

    // Reset user's information
    resetInfo() {
      this.$reset();
    },

   
    
    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm);
        setToken(res.data.token);
        agentInfo = res.data.agent_info;
        this.setInfo(res.data.agent_info);
console.log('res.data.agent_info::: ', res.data.agent_info);
      } catch (err) {
        clearToken();
        throw err;
      }
    },
    async info() {
console.log('agentInfo::: ', agentInfo);
      this.setInfo(agentInfo);
    },
    logoutCallBack() {
      const appStore = useAppStore();
      this.resetInfo();
      clearToken();
      removeRouteListener();
      appStore.clearServerMenu();
    },
    // Logout
    async logout() {
      try {
        await userLogout();
      } finally {
        this.logoutCallBack();
      }
    },
  },
});

export default useUserStore;
